package com.farm.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.farm.entity.CartItem;
import com.farm.entity.Product;
import com.farm.entity.User;
import com.farm.repository.CartItemRepository;
import com.farm.repository.ProductRepository;

@Service
public class CartService {

    @Autowired
    private CartItemRepository cartItemRepository;

    @Autowired
    private ProductRepository productRepository;

    public List<CartItem> getCartItems(User user) {
        return cartItemRepository.findByUser(user);
    }

    @Transactional
    public void addToCart(User user, Long productId, Integer quantity) {
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("商品不存在"));

        if (product.getStock() < quantity) {
            throw new RuntimeException("商品库存不足");
        }

        CartItem existingItem = cartItemRepository.findByUserAndProduct(user, product)
                .orElse(null);
                
        if (existingItem != null) {
            // 如果购物车中已有该商品，更新数量
            int newQuantity = existingItem.getQuantity() + quantity;
            if (product.getStock() < newQuantity) {
                throw new RuntimeException("商品库存不足");
            }
            existingItem.setQuantity(newQuantity);
            cartItemRepository.save(existingItem);
        } else {
            // 如果购物车中没有该商品，创建新的购物车项
            CartItem cartItem = new CartItem();
            cartItem.setUser(user);
            cartItem.setProduct(product);
            cartItem.setQuantity(quantity);
            cartItemRepository.save(cartItem);
        }
    }

    @Transactional
    public void updateCartItem(User user, Long productId, Integer quantity) {
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("商品不存在"));

        CartItem cartItem = cartItemRepository.findByUserAndProduct(user, product)
                .orElseThrow(() -> new RuntimeException("购物车中没有该商品"));

        if (quantity <= 0) {
            cartItemRepository.delete(cartItem);
        } else {
            if (product.getStock() < quantity) {
                throw new RuntimeException("商品库存不足");
            }
            cartItem.setQuantity(quantity);
            cartItemRepository.save(cartItem);
        }
    }

    @Transactional
    public void updateCartItemQuantity(User user, Long cartItemId, Integer quantity) {
        CartItem cartItem = cartItemRepository.findById(cartItemId)
                .orElseThrow(() -> new RuntimeException("购物车项不存在"));

        // 验证购物车项属于当前用户
        if (!cartItem.getUser().getId().equals(user.getId())) {
            throw new RuntimeException("无权操作此购物车项");
        }

        if (quantity <= 0) {
            cartItemRepository.delete(cartItem);
        } else {
            if (cartItem.getProduct().getStock() < quantity) {
                throw new RuntimeException("商品库存不足");
            }
            cartItem.setQuantity(quantity);
            cartItemRepository.save(cartItem);
        }
    }

    @Transactional
    public void removeCartItem(User user, Long cartItemId) {
        CartItem cartItem = cartItemRepository.findById(cartItemId)
                .orElseThrow(() -> new RuntimeException("购物车项不存在"));

        // 验证购物车项属于当前用户
        if (!cartItem.getUser().getId().equals(user.getId())) {
            throw new RuntimeException("无权操作此购物车项");
        }

        cartItemRepository.delete(cartItem);
    }

    @Transactional
    public void removeFromCart(User user, Long productId) {
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("商品不存在"));

        cartItemRepository.findByUserAndProduct(user, product)
                .ifPresent(cartItem -> cartItemRepository.delete(cartItem));
    }

    @Transactional
    public void clearCart(User user) {
        cartItemRepository.deleteByUser(user);
    }
} 